package com.zheng.common.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by admin on 2016/4/13.
 */
public class JsonUtil {

    static {
        System.setProperty("fastjson.compatibleWithJavaBean", "true");
    }

    /**
     * 获取String
     * @param object
     * @param key
     * @return
     */
    public static String getString(JSONObject object,String key){
        if(object!=null) {
            Object v = object.get(key);
            if (v != null)
                return v.toString();
        }
        return null;
    }

    public static Integer getInteger(JSONObject object,String key){
        if(object!=null){
            Object v = object.get(key);
            try{
                if(v!=null)
                    return Integer.valueOf(v.toString());
            }catch (NumberFormatException e){}
        }
        return null;
    }

    public static Double getDouble(JSONObject object,String key){
        if(object!=null) {
            Object v = object.get(key);
            try{
                if(v!=null)
                    return Double.valueOf(v.toString());
            }catch (NumberFormatException e){}
        }
        return null;
    }

    public static JSONObject getJSONObject(JSONObject object,String key){
        if(object!=null) {
            Object v = object.get(key);
            try{
                if(v!=null)
                    return JSONObject.parseObject(v.toString());
            }catch (Exception e){}
        }
        return null;
    }

    public static String object2Json(Object object) {
        if (object == null) {
            return null;
        }
        return JSONObject.toJSONString(object);
    }

    /**
     * <B>方法名称：</B>将JSONObject对象转换为实体对象<BR>
     * <B>概要说明：</B>将JSONObject对象转换为实体对象<BR>
     * @param data JSONObject对象
     * @param clzss 转换对象
     * @return T
     */
    public static <T> T getObjectFromJson(String json, Class<T> clazz) {
        if (json == null) {
            return null;
        }
        return JSON.parseObject(json, clazz);
    }
    /**
     * <B>方法名称：</B>将JSON字符串数组转为List集合对象<BR>
     * <B>概要说明：</B>将JSON字符串数组转为List集合对象<BR>
     * @param data JSON字符串数组
     * @param clzss 转换对象
     * @return List<T>集合对象
     */
    public static <T> List<T> getObjectListFromJson(String json, Class<T> clazz) {
        if (json == null) {
            return null;
        }
        return JSON.parseArray(json, clazz);
    }
    /**
     * <B>方法名称：</B>将List<JSONObject>转为List集合对象<BR>
     * <B>概要说明：</B>将List<JSONObject>转为List集合对象<BR>
     * @param data List<JSONObject>
     * @param clzss 转换对象
     * @return List<T>集合对象
     */
    public static <T> List<T> convertJSONToArray(List<JSONObject> data, Class<T> clzss) {
        try {
            List<T> t = new ArrayList<T>();
            for (JSONObject jsonObject : data) {
                t.add(getObjectListFromJson(jsonObject, clzss));
            }
            return t;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    /**
     * <B>方法名称：</B>将JSONObject对象转换为实体对象<BR>
     * <B>概要说明：</B>将JSONObject对象转换为实体对象<BR>
     * @param data JSONObject对象
     * @param clzss 转换对象
     * @return T
     */
    public static <T> T getObjectListFromJson(JSONObject data, Class<T> clzss) {
        try {
            T t = JSONObject.toJavaObject(data, clzss);
            return t;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    /**
     * <B>方法名称：</B>将JSON字符串数组转为List集合对象<BR>
     * <B>概要说明：</B>将JSON字符串数组转为List集合对象<BR>
     * @param data JSON字符串数组
     * @param clzss 转换对象
     * @return List<T>集合对象
     */
    public static <T> List<T> convertJSONToArray(String data, Class<T> clzss) {
        try {
            List<T> t = JSON.parseArray(data, clzss);
            return t;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    public static JSONObject getJSONObjectFromJson(String json) {
        if (json == null) {
            return null;
        }
        return JSONObject.parseObject(json);
    }

    public static JSONObject getJSONObjectFromObj(Object object) {
        if (object == null) {
            return null;
        }
        return (JSONObject) JSONObject.toJSON(object);
    }

    /**
     * JSON转Map
     * @param jsonStr
     * @return
     */

    @SuppressWarnings("rawtypes")
    public static Map<String, Object> parseJSON2Map(String jsonStr){
        Map<String, Object> map = new HashMap<String, Object>();
        //最外层解析
        JSONObject json = JSONObject.parseObject(jsonStr);
        for(Object k : json.keySet()){
            Object v = json.get(k);
            //如果内层还是数组的话，继续解析
            if(v instanceof JSONArray){
                //数组对象又分为两种（简单数组或键值对）
                List list = parseJSON2List(json.get(k).toString());
                map.put((String)k, list);
            } else {
                map.put((String)k, v);
            }
        }
        return map;

    }
    /**
     * JSON转List<Map<String, Object>>
     * @param json
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static List<Map<String, Object>> parseJSON2List(String json){
        JSONArray jsonArray = JSONArray.parseArray(json);
        List list = new ArrayList();
        for (Object object : jsonArray) {
            try {
                JSONObject jsonObject = (JSONObject) object;
                HashMap<String, Object> map = new HashMap<String, Object>();
                for (Map.Entry entry : jsonObject.entrySet()) {
                    if(entry.getValue() instanceof  JSONArray){
                        map.put((String)entry.getKey(), parseJSON2List(entry.getValue().toString()));
                    }else{
                        map.put((String)entry.getKey(), entry.getValue());
                    }
                }
                list.add(map);
            } catch (Exception e) {
                list.add(object);
            }
        }
        return list;

    }
    /**
     * List转JSON<Map<String, Object>>
     * @param json
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static JSONArray parseList2JSON(List list){
        if(list == null){
            return null;
        }
        try {
            JSONArray array = JSONArray.parseArray(JSON.toJSONString(list));
            return array;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void outJsonObj(HttpServletResponse response, Object json) throws Exception{
        try {
            response.setContentType("application/json;charset=UTF-8");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Charset", "utf-8");
            PrintWriter out = response.getWriter();
            out.print(JSONObject.toJSON(json).toString());
            out.flush();
            out.close();
        } catch (Exception e) {
            throw e;
        }
    }
}
